package br.com.invest.action;

import br.com.invest.model.Grupo;
import java.util.logging.Level;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.BCodec;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

/**
 *
 * @author Kirmaier
 */
@Name("Authentication")
public class AuthenticationController {

    @Logger
    private Log log;
    @In
    private Session investDB;
    // @Out 
    private Grupo usuario;

    public boolean logon() {
        try {
            log.info("authenticando usuario", "{identity.username}");

            String criptografia = null;
            BCodec bc = new BCodec();
            criptografia = Identity.instance().getPassword();

            Identity.instance().setPassword(bc.encode(criptografia));

            if (Identity.instance().getPassword().equals("") ||
                    Identity.instance().getUsername().equals("")) {

                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Usuário ou senha inválidos!", ""));

                return false;
            } else if (!Identity.instance().getPassword().equals("") &&
                    !Identity.instance().getUsername().equals("")) {

                Criteria c = investDB.createCriteria(Grupo.class);
                c.add(Restrictions.eq("senha", Identity.instance().getPassword()));


                usuario = (Grupo) c.uniqueResult();

                if (usuario == null) {
                    log.error("ERROR", "Usuario ou senha invalidos");
                    FacesContext.getCurrentInstance().addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, "Usuário ou senha inválidos!", ""));

                    return false;

                } else {
                    return true;
                }
            }

        } catch (EncoderException ex) {
            ex.printStackTrace();
            java.util.logging.Logger.getLogger(AuthenticationController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }
}
